<template>
  <el-dialog title="用户画像" v-model="visible" width="900px" :append-to-body="true" @close="close">
    <el-button size="small" type="primary" :icon="Plus" style="margin-bottom: 5px" @click="openForm(null)">添加</el-button>
    <el-table :data="tableList" stripe border :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}" size="small">
      <el-table-column label="名称" prop="name" width="120"/>
      <el-table-column label="内容" prop="tags"/>
      <el-table-column label="创建时间" prop="createTime" width="140"/>
      <el-table-column label="操作" width="140">
        <template v-slot="{row}">
          <el-button size="small" :icon="Edit" type="primary" text @click="openForm(row)">编辑</el-button>
          <el-button size="small" :icon="Delete" type="danger" text @click="removeData(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="formData.id ? '编辑' : '添加'" v-model="formVisible" width="450px" :append-to-body="true">
      <el-form :model="formData" :rules="formRules" size="small" ref="formRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请填写画像标签名称" maxlength="32" clearable/>
        </el-form-item>
        <el-form-item label="标签" prop="value">
          <el-tag v-for="(tag, index) in tags" :key="tag" style="margin: 0 5px 5px 0" closable @close="removeTag(index)">{{ tag }}</el-tag>
          <el-input v-if="tagInputVisible" v-model="inputTag" size="small" @keyup.enter="confirmTag" @blur="confirmTag" style="width: 80px;height: 20px;margin-bottom: 5px"/>
          <el-button v-else type="primary" text style="margin-bottom: 5px" @click="tagInputVisible = true">添加标签</el-button>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button size="small" @click="formVisible = false">取消</el-button>
        <el-button size="small" type="primary" :loading="submitLoad" @click="submit(formRef)">提交</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button size="small" type="primary" @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, toRefs, ref} from 'vue'
import {Edit, Plus, Delete} from '@element-plus/icons-vue'
import {ElMessageBox, ElMessage} from 'element-plus'
import customerPortraitApi from '/@/api/ums/customer/portrait'

export default {
  name: 'UserLabel',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dataList: {
      type: Array,
      default: []
    },
    customerId: {
      type: String,
      default: null
    }
  },
  emits: ['callback', 'update:dialogVisible'],
  setup(props, context) {
    const formRef = ref()
    const {dialogVisible, dataList, customerId} = toRefs(props)
    const visible = computed({
      get: () => {
        if (dialogVisible.value) {
          state.tableList = dataList.value
        }
        return dialogVisible.value
      },
      set: val => context.emit('update:dialogVisible', val)
    })
    const state = reactive({
      formData: {
        id: null,
        customerId: null,
        name: null,
        tags: null
      },
      formRules: {
        name: {required: true, message: '请填写画像标签名称', trigger: 'blur'}
        // value: {required: true, message: '请填写画像标签内容', trigger: 'blur'}
      },
      formVisible: false,
      submitLoad: false,
      tableList: [],
      tags: [],
      inputTag: null,
      tagInputVisible: false,
    })

    const refreshList = () => customerPortraitApi.getList(customerId.value).then(res => state.tableList = res.data).catch(e => console.log(e))
    const removeTag = (index) => state.tags.splice(index, 1)
    const confirmTag = () => {
      if (state.inputTag && state.inputTag.trim()) {
        state.tags.push(state.inputTag)
      }
      state.inputTag = null
      state.tagInputVisible = false
    }
    const openForm = (item) => {
      if (item && item.id) {
        state.formData = JSON.parse(JSON.stringify(item))
        state.tags = state.formData.tags.split(',')
      } else {
        state.tags = []
        state.formData = {
          id: null,
          customerId: customerId.value,
          name: null,
          tags: null
        }
      }
      state.formVisible = true
    }
    const removeData = (item) => {
      ElMessageBox.confirm(`确定删除画像标签 ${item.name} ？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        customerPortraitApi.remove(item).then(res => {
          if (res.data) {
            ElMessage.success('删除成功！')
            refreshList()
          }
        }).catch(e => console.log(e))
      }).catch(() => {
      })
    }
    const submit = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return
        }
        if (!state.tags || state.tags.length < 0) {
          return ElMessage.warning('请填写画像标签')
        }
        state.formData.tags = state.tags + ''
        state.submitLoad = true
        let res
        try {
          if (state.formData.id) {
            res = await customerPortraitApi.edit(state.formData)
          } else {
            res = await customerPortraitApi.create(state.formData)
          }
          if (res.data) {
            ElMessage.success('保存成功！')
            refreshList()
            state.formVisible = false
          }
        } catch (e) {
          console.log(e)
        }
        state.submitLoad = false
      })
    }
    const close = () => context.emit('callback')

    return {
      Plus,
      Edit,
      Delete,
      visible,
      formRef,
      ...toRefs(state),
      close,
      openForm,
      removeData,
      submit,
      removeTag,
      confirmTag
    }
  }
}
</script>

<style scoped lang="scss">
</style>
